<template>
  <template v-if="isAlready">
    <el-container style="margin-bottom: -60px;">
      <el-header>
        <div class="left-panel">
          <fsButton ref="button" plain size="default" :buttons="buttons" @clickHandler="buttonHandler"></fsButton>
        </div>
        <div class="right-panel">
          <ex-search ref="search" :searches="searches" @searchOk="searchHandler" default-code="code" placeholder="请输入资产编码" :fixedParam="{mainAssetId:model.assetId||model.id||'default',excludeStatus:['delete']}"></ex-search>
        </div>
      </el-header>
      <el-main class="nopadding" style="padding-bottom: 15px;">
        <ex-table :id="'exTable'+widget.id" ref="table" :height="380" :columns="columns" :url="apiUrl" size="small" :refs="this.$refs" search="search" :params="{mainAssetId:model.assetId||model.id||'default'}" @columnClick="columnClickHandler"></ex-table>
      </el-main>
    </el-container>
    <data-card ref="dataCard"></data-card>
    <asset-selecter ref="assetSelecter" :ids="assetIds" @success="assetSelectHandler"></asset-selecter>
  </template>
</template>
<script>

import draggable from "vuedraggable";
import ExFormItem from "@/components/exFormItem/index.vue";
import ExTable from "@/components/exTable/index.vue";
import cache from "@/utils/cache";
import {defineAsyncComponent} from "vue";
import ExSelector from "@/components/exSelector/index.vue";
import ExSelect from "@/components/exSelect/index.vue";
import tool from "@/utils/tool";
import BaseTemplate from "@/utils/baseTemplate";
import ExSearch from "@/components/exSearch/index.vue";
import http from "@/utils/request";


export default {
  name: "wAssetAccessory",
  computed: {
    cache() {
      return cache
    }
  },
  components: {
    AssetSelecter:defineAsyncComponent(()=>import("@/views/asset/asset/asset-selecter.vue")),
    ExSearch,
	  ExSelect,
	  ExSelector,
	  DataCard:defineAsyncComponent(()=>import("@/views/asset/card/card.vue")), ExTable, ExFormItem, draggable},
  props: {
    model: {type: Object, default: {}},
    widget: {type: Object, default: null},
    drag: {type: Boolean, default: false},
  },
  data() {
    return {
      dialog: {
        save: false,
        permission: false,
      },
      apiObj: [],
      buttons: [

      ],
      searches: [
        {type: "input", name: "资产编码", code: "code", placeholder: "请输入资产编码", maxlength: 30, showLimit: true},
        {type: "input", name: "财务编码", code: "financialCode", placeholder: "请输入财务编码"},
        {type: "tree-select", name: "资产类别", code: "assetCategoryIds", placeholder: "请选择资产类别", dictCode:'FamsAssetCategory',checkStrictly:true,multiple:true},
        {type: "select", name: "资产状态", code: "assetStatusIds", placeholder: "请选择资产状态", dictCode:'ASSET_STATUS',multiple:true},
      ],
      columns: [
        {code: "assetStatusId", name: "资产状态", width:"85",formatter:"DICT",key: "ASSET_STATUS",sortable:true},
        {code: "code", name: "资产编码", width:"135",click:"show1"},
        {code: "financialCode", name: "财务编码", width:"170"},
        {code: "name", name: "资产名称", width:"200"},
        {code: "brand", name: "品牌", width:""},
        {code: "model", name: "规格型号", width:""},
        {code: "assetCount", name: "数量", width:"70",summary:true},
        {code: "usingMenId", name: "使用人", width:"110",formatter: "DICT",key: "SysUser"},
        {code: "usingDepartmentId", name: "使用部门", width:"220",formatter: "DICT",key: "SysOrganization"},
        {code: "originalValue", name: "资产原值", width:"150",summary:true},
        {code: "netValue", name: "资产净值", width:"150",summary:true},
        {code: "mainCategoryCode", name: "资产大类",width:"110", formatter:"DICT",key: "FamsAssetCategory",sortable:true},
        {code: "assetCategoryId", name: "资产小类",width:"220", formatter:"DICT",key: "FamsAssetCategory",sortable:true},
        {code: "storePlaceId", name: "资产位置",width: "220", formatter:"DICT",key: "FamsPosition",sortable:true},
        {code: "boughtDate", name: "购置日期", width:"110",formatter: "DATE",sortable:true},
      ],
      parentLevelCode:"",
      assetIds:[],
      loading: false,
      loginUsers: tool.current.user(),
      isAlready: false,
      apiUrl: null,
    }
  },
  created() {
    if(!this.drag){
      this.apiUrl = this.$API.asset.asset.list.url;
      let manageDeptIds = tool.current.manageDeptIds();
      if(manageDeptIds.includes(this.model.usingDepartmentId)||manageDeptIds.includes(this.model.dutyDepartmentId)){
        this.buttons.push({name: "添加", icon: "el-icon-circle-plus", click: "bindAccessory", type: "primary", permission: ""});
        this.buttons.push({name: "移除", icon: "el-icon-remove", click: "unBindAccessory", type: "info", permission: ""});
      }
      this.buttons.push({name: "导出", icon: "el-icon-download", click: "export", type: "info", permission: ""});
    }
    this.isAlready = true;
  },
  mounted() {
  },
  beforeMount() {

  },
  methods: {
    buttonHandler(index, name) {
      this.$options.methods[name](this, index);
    },
    async searchTreeHandler(data) {
      let queryParams = {pathCode:data.levelCode}
      this.parentLevelCode= data.levelCode;
      await this.$refs.table.refresh(queryParams);
    },

    async searchHandler() {
      let queryParams = {pathCode: this.parentLevelCode}
      await this.$refs.table.refresh(queryParams);
    },
    columnClickHandler(name,data){
      this.$options.methods[name](this, data);
    },
    //查看
    async show1(_this, row) {
      let assetCategory = await _this.$cache.data.loadAssetCategory(row.assetCategoryId);
      try {
        _this.loading = true;
        let entity = {cardId: assetCategory.assetCardId, _editFlag: false}
        _this.$nextTick(() => {
          _this.cardPreview = false;
          _this.$refs.dataCard.open(Object.assign(entity, row));
        });
      } finally {
        _this.loading = false;
      }
    },
    async bindAccessory(_this, row) {
		if(_this.model.isLocked!=='0'){
			_this.$message.warning("资产被业务单据锁定，解锁后才能进行此操作!");
			return ;
		}
      _this.$nextTick(async () => {
        _this.assetIds = [];
        let queryParams = {
          isAccessory:'1',//只查配件信息
          financialTypes:['in'],//只查财务类型为账内的资产
          excludeStatus:['scrap','delete'],//排除报废和删除资产
		  isBindMainAsset:'0',//只查未绑定主资产的资产
          // deptIds: _this.$TOOL.current.manageDeptIds(),
		  usingDepartmentId: _this.model.usingDepartmentId,//只查询使用部门与主资产在同一部门的配件
        };
        _this.$refs.assetSelecter.open(queryParams);
      })
    },
    async assetSelectHandler() {
      let bindData = {mainAssetId: this.model.assetId||this.model.id||'default', accessoryAssetIds: this.assetIds};
      let rsp = await this.$API.asset.asset.bindAccessory.post(bindData);
      if(rsp.code===2000){
        this.$message.success(this.$t("code." + rsp.code));
        this.searchHandler();
      }
    },
    async unBindAccessory(_this, index) {
      try {
		  if(_this.model.isLocked!=='0'){
			  _this.$message.warning("资产被业务单据锁定，解锁后才能进行此操作!");
			  return ;
		  }
        _this.$refs.button.loading(index, true);
        let selections = _this.$refs.table.selections();
        let unBindData = {
          accessoryAssetIds:[],
        }
        if (selections.length === 0) {
          let confirm = await _this.$confirm('是否解绑当前资产的所有配件?',  _this.$t('common.warn'), {type: 'warning'}).then(() => {return true;}).catch(() => {return false;});
          if (!confirm) return;
          //请求数据加载
          let queryParams = _this.$refs.table.queryParams();
          let rsp = await http.post(_this.$API.asset.asset.selectAssetIds.url, queryParams);
          if (rsp.code===2000) {
            let assetIds = rsp.data;
            if(Array.isArray(assetIds)){
             unBindData.accessoryAssetIds = assetIds;
            }
          }
        }else{
          let confirm = await _this.$confirm('是否将选择的配件解除关联绑定关系?',  _this.$t('common.warn'), {type: 'warning'}).then(() => {return true;}).catch(() => {return false;});
          if (!confirm) return;

          let assetIds = [];
          for (let index = 0; index < selections.length; index++) {
            const element = selections[index];
            assetIds.push(element.id);
          }
          unBindData.accessoryAssetIds = assetIds;
        }

        if(unBindData.accessoryAssetIds.length>0){
          let res = await _this.$API.asset.asset.unBindAccessory.post(unBindData);
          if (res.code === 2000) {
            _this.$message.success(_this.$t("code."+res.code));
            _this.searchHandler();
          }
        }else{
          _this.$message.warning('没有解绑的配件');
        }
      }catch (e){
        console.log(e);
      }finally {
        _this.$refs.button.loading(index, false);
      }
    },
    //导出
    async export(_this,index) {
      let preName = _this.model.assetCode||_this.model.code||'';
      let attachParams = {};
      attachParams.exportType = "accessoryAsset";
      attachParams.exportName=preName+"资产配件";
      let exportApi = _this.$API.asset.asset.export;
      let exTableRef = _this.$refs.table;
      let exportBtnRef = _this.$refs.button;
      let exportBtnIndex = index;
      await BaseTemplate.export(_this, exportApi, attachParams, exportBtnRef, exportBtnIndex, exTableRef);
    },
  }
}
</script>
<style>
.tableItemClass {
  cursor: move;
  float: left;
  background: #fff;
  height: 35px;
  text-align: center;
  horiz-align: center;
  border: 1px dashed #e6e6e6;
}

.tableItemClass:hover {
  border-color: rgb(71, 231, 250);
}

.tableDragAreaClass {
  height: 40px;
  background: rgba(243, 149, 95, 0.1);
}
</style>
